package com.lagou.rocket.demo.order.service.Impl;

import com.lagou.rocket.demo.order.model.Inventory;
import com.lagou.rocket.demo.order.model.Order;
import com.lagou.rocket.demo.order.repository.OrderRepository;
import com.lagou.rocket.demo.order.service.IInventoryService;
import com.lagou.rocket.demo.order.service.IOrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *
 * </p>
 *
 * @author KK
 * @since 2021-11-07
 */
@Service
public class OrderServiceImpl implements IOrderService {

    private final OrderRepository orderRepository;
    private final IInventoryService inventoryService;


    public OrderServiceImpl(OrderRepository orderRepository, IInventoryService inventoryService) {
        this.orderRepository = orderRepository;
        this.inventoryService = inventoryService;
    }



    @Override
    public Order save(Order order) {

        return orderRepository.save(order);
    }

    @Override
    public Order getOne(Long id) {
        return orderRepository.getOne(id);
    }

    @Transactional
    @Override
    public String checkOrderStatusAndRestoreInventoryIfNeeded(Long orderId) {
        // 应该是幂等方法， 幂等保证： 只有状态是unpaid， 才能修改库存

        //检查订单是否已经支付;(共享锁查询)
        Order order = orderRepository.getOrderById(orderId);

        if (order == null){
            return null;
        }

        //如果未支付:
        if ("unpaid".equals(order.getStatus())){
            //  修改订单的支付状态未支付超时;
            order.setStatus("overtime");
            orderRepository.save(order);
            //  增加库存;
            Inventory inventory = inventoryService.getInventoryByProductCode(order.getProductCode());
            inventory.setInventory(inventory.getInventory() + 1);
            inventoryService.save(inventory);
            return order.getProductCode();
        }

        return null;

    }

    @Override
    public String getOrderStatus(Long id) {
        Order one = orderRepository.getOne(id);
        return (one == null)
                ? null : one.getStatus();
    }

    @Transactional
    @Override
    public String pay(Long userId, Long id) {

        // 检查订单状态是否超时,
        final Order order = orderRepository.getOrderById(id);
        if (order == null){
            return null;
        }

        //​ 未超时, 修改为支付状态;
        if ("unpaid".equals(order.getStatus())){
            order.setStatus("paid");
            orderRepository.save(order);
            return "OK";
        }else{
            //​ 超时, 跳转到历史订单页面;
            return order.getStatus();
        }
    }


}
